package com.culturalCenter.dataCenter.controller.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.culturalCenter.dataCenter.Utils.ApiResult;
import com.culturalCenter.dataCenter.Utils.ResultCode;
import com.culturalCenter.dataCenter.customEntity.responseParam.training.*;
import com.culturalCenter.dataCenter.customEntity.training.*;
import com.culturalCenter.dataCenter.entity.site.SiteAlerts;
import com.culturalCenter.dataCenter.entity.training.TrainingMonitorPersonnel;
import com.culturalCenter.dataCenter.globalconfig.Interface.ApiVersion;
import com.culturalCenter.dataCenter.globalconfig.Interface.CustomVersion;
import com.culturalCenter.dataCenter.param.ResourceDistributionTableParam;
import com.culturalCenter.dataCenter.param.latestResourceRecommendParam;
import com.culturalCenter.dataCenter.service.training.*;
import com.culturalCenter.dataCenter.vo.TrainingDatartVo;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

import static com.culturalCenter.dataCenter.Utils.ApiResult.instance;

/**
 * 培训
 *
 * @author : weicai
 * @date : 10:50 2020/9/22
 */
@RestController
@RequestMapping("/{version}/training")
@Api(tags = "培训模块")
@ApiVersion(CustomVersion.VERSION_1)
@Slf4j
public class TrainingController {

    @Resource
    private TrainingService trainingService;
    @Resource
    private TrainingTimeLineService trainingTimeLineService;
    @Resource
    private TrainingAudienceService trainingAudienceService;
    @Resource
    private TrainingPopularAnalysisService trainingPopularAnalysisService;
    @Resource
    private TrainingAssessmentService trainingAssessmentService;
    @Resource
    private TrainingResourceService trainingResourceService;
    @Resource
    private TrainingSiteMonitorService trainingSiteMonitorService;
    @Resource
    private TrainingPromotionAnalysisService trainingPromotionAnalysisService;
    @Value("${tuchuang.hostname}")
    private String hostname;
    @Value("${whg.orgId}")
    private String orgId;
    @Value("${tuchuang.imgOssUrl}")
    private String imgOssUrl;
    @Resource
    private RestTemplate restTemplate;

    /**
     * 培训_首页
     */
    @GetMapping("/menu")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "branchId", value = "分馆id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startDate", value = "开始日期", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endDate", value = "结束日期", paramType = "query", dataType = "String")
    })
    @ApiOperation(value = "培训首页", notes = "培训首页，可切换不同分馆")
    public ApiResult<TrainingMenuResponse> trainingMenu(@RequestParam String branchId, String startDate, String endDate,String type) {
        TrainingMenuResponse trainingMenuResponse = trainingService.getTrainingMenu(branchId, startDate, endDate,type);
        return instance(ResultCode.SUCCESS, trainingMenuResponse);
    }

    /**
     * 培训_左侧列表
     */
    @GetMapping("/trainingList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keywords", value = "关键字", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "branchId", value = "分馆id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "页码尺寸", paramType = "query", dataType = "int")
    })
    @ApiOperation(value = "培训左侧列表", notes = "培训左侧列表，可切换不同分馆")
    public ApiResult<TrainingListResponse> getTrainingList(@RequestParam(required = false) String keywords,
                                                           @RequestParam(required = false) String status,
                                                           @RequestParam String branchId,
                                                           @RequestParam(required = false, defaultValue = "1") int pageNum,
                                                           @RequestParam(required = false, defaultValue = "15") int pageSize) {
        TrainingListResponse trainingListResponse = trainingService.getTrainingList(keywords, status, branchId, pageNum, pageSize);
        return instance(ResultCode.SUCCESS, trainingListResponse);
    }

    /**
     * 培训_基本信息
     */
    @GetMapping("/trainingInfo")
    @ApiOperation(value = "培训课程基本信息", notes = "培训课程基本信息")
    @ApiImplicitParams(@ApiImplicitParam(name = "trainingId", value = "培训课程id", paramType = "query", dataType = "String"))
    public ApiResult<CustomTrainingInfo> getTrainingInfo(@RequestParam String trainingId) {
        CustomTrainingInfo trainingInfo = trainingService.getTrainingInfo(trainingId);
        return instance(ResultCode.SUCCESS, trainingInfo);
    }

    /**
     * 培训_基本信息_详情
     */
    @GetMapping("/trainingInfo/detail")
    @ApiOperation(value = "培训课程信息详情", notes = "培训课程信息详情")
    @ApiImplicitParams(@ApiImplicitParam(name = "trainingId", value = "培训课程id", paramType = "query", dataType = "String"))
    public ApiResult<TrainingInfoDetailResponse> getTrainingInfoDetail(@RequestParam String trainingId) {
        TrainingInfoDetailResponse trainingInfoDetailResponse = trainingService.getTrainingInfoDetail(trainingId);
        return instance(ResultCode.SUCCESS, trainingInfoDetailResponse);
    }

    /**
     * 时间轴
     */
    @GetMapping("/timeLine")
    @ApiOperation(value = "时间轴", notes = "时间轴")
    @ApiImplicitParams(@ApiImplicitParam(name = "trainingId", value = "培训课程id", paramType = "query", dataType = "String"))
    public ApiResult<TrainingTimeLineResponse> getTimeLine(@RequestParam String trainingId) {
        TrainingTimeLineResponse trainingTimeLineResponse = trainingTimeLineService.getTimeLine(trainingId);
        return instance(ResultCode.SUCCESS, trainingTimeLineResponse);
    }

    /**
     * 时间轴_申请表格
     */
    @GetMapping("/timeLine/apply/table")
    @ApiOperation(value = "申请表格", notes = "申请表格")
    @ApiImplicitParams(@ApiImplicitParam(name = "trainingId", value = "培训课程id", paramType = "query", dataType = "String"))
    public ApiResult<TrainingInfoDetailResponse> getApplyTable(@RequestParam String trainingId) {
        TrainingInfoDetailResponse trainingInfoDetailResponse = trainingService.getTrainingInfoTableDetail(trainingId);
        return instance(ResultCode.SUCCESS, trainingInfoDetailResponse);
    }

    /**
     * 时间轴_报名清单
     */
    @GetMapping("/timeLine/registration/list")
    @ApiOperation(value = "报名清单", notes = "报名清单")
    @ApiImplicitParams(@ApiImplicitParam(name = "trainingId", value = "培训课程id", paramType = "query", dataType = "String"))
    public ApiResult<List<CustomRegistrationList>> getRegistrationCheckList(@RequestParam String trainingId) {
        List<CustomRegistrationList> registrationCheckList = trainingTimeLineService.getRegistrationListByTrainingId(trainingId);
        return instance(ResultCode.SUCCESS, registrationCheckList);
    }

    /**
     * 时间轴_中签清单
     */
    @GetMapping("/timeLine/winning/list")
    @ApiOperation(value = "中签清单", notes = "中签清单")
    @ApiImplicitParams(@ApiImplicitParam(name = "trainingId", value = "培训课程id", paramType = "query", dataType = "String"))
    public ApiResult<List<CustomTrainingWinningList>> getWinningCheckList(@RequestParam String trainingId) {
        List<CustomRegistrationList> winningList = trainingTimeLineService.getWinningListByTrainingId(trainingId);
        return instance(ResultCode.SUCCESS, winningList);
    }

    /**
     * 时间轴_签到清单
     */
    @GetMapping("/timeLine/signIn/list")
    @ApiOperation(value = "签到清单", notes = "签到清单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "periodsId", value = "期数id", paramType = "query", dataType = "String")
    })
    public ApiResult<List<CustomSignInList>> getSignInCheckList(@RequestParam String periodsId) {
        List<CustomSignInList> signInList = trainingTimeLineService.getSignInListByTrainingId(periodsId);
        return instance(ResultCode.SUCCESS, signInList);
    }

    /**
     * 时间轴_考勤清单
     */
    @GetMapping("/timeLine/attendance/list")
    @ApiOperation(value = "考勤清单", notes = "考勤清单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "trainingId", value = "培训课程id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "periodsId", value = "期数id", paramType = "query", dataType = "String")
    })
    public ApiResult<List<CustomAttendanceList>> getAttendanceCheckList(@RequestParam String periodsId) {
        List<CustomAttendanceList> attendanceList = trainingTimeLineService.getAttendanceListByTrainingId(periodsId);
        return instance(ResultCode.SUCCESS, attendanceList);
    }

    /**
     * 时间轴_现场_监控画面/现场监控_异常情况_监控画面
     */
    @GetMapping("/timeLine/monitorPicture")
    @ApiOperation(value = "现场监控", notes = "现场监控")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "警报id", paramType = "query", dataType = "String")
    })
    public ApiResult<List<SiteAlerts>> getMonitorPicture(@RequestParam String id) {
        List<SiteAlerts> monitorPictureList = trainingTimeLineService.getMonitorPicture(id);
        return instance(ResultCode.SUCCESS, monitorPictureList);
    }

    /**
     * 受众分析
     */
    @GetMapping("/audienceAnalysis")
    @ApiOperation(value = "受众分析", notes = "受众分析")
    @ApiImplicitParams(@ApiImplicitParam(name = "trainingId", value = "培训课程id", paramType = "query", dataType = "String"))
    public ApiResult<TrainingAudienceAnalysisResponse> getAudienceAnalysisData(@RequestParam String trainingId) {
        TrainingAudienceAnalysisResponse trainingAudienceAnalysisResponse = trainingAudienceService.getAudienceAnalysisData(trainingId);
        return instance(ResultCode.SUCCESS, trainingAudienceAnalysisResponse);
    }

    /**
     * 推广分析
     */
    @GetMapping("/promotionAnalysis")
    @ApiOperation(value = "推广分析", notes = "推广分析")
    @ApiImplicitParams(@ApiImplicitParam(name = "trainingId", value = "培训课程id", paramType = "query", dataType = "String"))
    public ApiResult<TrainingPromotionAnalysisResponse> getPromotionAnalysis(@RequestParam String trainingId) {
        TrainingPromotionAnalysisResponse trainingPromotionAnalysisResponse = trainingPromotionAnalysisService.getPromotionAnalysis(trainingId);
        return instance(ResultCode.SUCCESS, trainingPromotionAnalysisResponse);
    }

    /**
     * 受欢迎分析
     */
    @GetMapping("/popularAnalysis")
    @ApiOperation(value = "受欢迎分析", notes = "受欢迎分析")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "trainingId", value = "培训课程id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "branchId", value = "分馆id", paramType = "query", dataType = "String")
    })
    public ApiResult<TrainingPopularAnalysisResponse> getPopularAnalysisData(@RequestParam String trainingId, String branchId) {
        TrainingPopularAnalysisResponse trainingPopularAnalysisResponse = trainingPopularAnalysisService.getPopularAnalysisData(trainingId, branchId);
        return instance(ResultCode.SUCCESS, trainingPopularAnalysisResponse);
    }

    /**
     * 受欢迎分析_评分评论列表
     */
    @GetMapping("/popularAnalysis/comment/list")
    @ApiOperation(value = "受欢迎分析_评分评论列表", notes = "受欢迎分析_评分评论列表")
    @ApiImplicitParams(@ApiImplicitParam(name = "trainingId", value = "培训课程id", paramType = "query", dataType = "String"))
    public ApiResult<List<CustomCommentList>> getCommentList(@RequestParam String trainingId) {
        List<CustomCommentList> commentList = trainingPopularAnalysisService.getCommentList(trainingId);
        return instance(ResultCode.SUCCESS, commentList);
    }

    /**
     * 图片视频（没用了）
     */
//    @GetMapping("/resource")
//    @ApiOperation(value = "图片视频", notes = "图片视频")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "trainingId", value = "培训课程id", paramType = "query", dataType = "String"),
//            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query", dataType = "int"),
//            @ApiImplicitParam(name = "pageSize", value = "页码尺寸", paramType = "query", dataType = "int")
//    })
//    public ApiResult<TrainingResourceResponse> getPictureAndVideo(@RequestParam String trainingId, @RequestParam(required = false, defaultValue = "1") int pageNum, @RequestParam(required = false, defaultValue = "10") int pageSize) {
//        TrainingResourceResponse trainingResourceResponse = trainingResourceService.getPictureAndVideo(trainingId, pageNum, pageSize);
//        return instance(ResultCode.SUCCESS, trainingResourceResponse);
//    }

    /**
     * 现场监控
     */
    @GetMapping("/monitor")
    @ApiOperation(value = "现场监控", notes = "现场监控")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "trainingId", value = "培训课程id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "periodsId", value = "期数id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "页码尺寸", paramType = "query", dataType = "int")
    })
    public ApiResult<TrainingSiteMonitorResponse> getSiteMonitor(@RequestParam String trainingId,
                                                                 @RequestParam(required = false) String periodsId,
                                                                 @RequestParam(required = false, defaultValue = "1") int pageNum,
                                                                 @RequestParam(required = false, defaultValue = "10") int pageSize) {
        TrainingSiteMonitorResponse trainingSiteMonitorResponse = trainingSiteMonitorService.getSiteMonitor(trainingId, periodsId, pageNum, pageSize);
        return instance(ResultCode.SUCCESS, trainingSiteMonitorResponse);
    }

    /**
     * 现场监控_异常情况（不包含图片，图片调的上面的接口，和时间轴混在一起的那个）
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "periodsId", value = "期数id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "页码尺寸", paramType = "query", dataType = "int")
    })
    @ApiOperation(value = "现场监控_异常情况", notes = "现场监控_异常情况")
    @GetMapping("/monitor/exception")
    public ApiResult<PageInfo<SiteAlerts>> getException(String periodsId, int pageNum, int pageSize) {
        PageInfo<SiteAlerts> exceptionList = trainingSiteMonitorService.getException(periodsId, pageNum, pageSize);
        return instance(ResultCode.SUCCESS, exceptionList);
    }

    /**
     * 现场监控_出入人员_监控画面
     */
    @GetMapping("/monitor/picture")
    @ApiOperation(value = "现场监控_出入人员_监控画面", notes = "现场监控_出入人员_监控画面")
    public ApiResult<TrainingMonitorPersonnel> getPersonMonitorPicture(@RequestParam String id) {
        TrainingMonitorPersonnel monitorPicture = trainingSiteMonitorService.getPersonMonitorPicture(id);
        return instance(ResultCode.SUCCESS, monitorPicture);
    }

    /**
     * datart获取培训表数据
     */
    @GetMapping("/table")
    @ApiOperation(value = "", notes = "")
    public String getTrainingTable() {
        List<TrainingDatartVo>trainingTable = trainingService.getTrainingTable();
        String jsonString = JSON.toJSONString(trainingTable, SerializerFeature.WriteNullStringAsEmpty);
        return jsonString;
    }

    /**
     * 资源模块
     */
    @GetMapping("/resource")
    @ApiOperation(value = "", notes = "")
    public ApiResult getResource() {
        Map resource = trainingService.getResource();
        return instance(ResultCode.SUCCESS,resource);
    }

    /**
     * 数据屏-资源分布表
     */
    @GetMapping("/resourceDistributionTable")
    @ApiOperation(value = "数据屏-资源分布表")
    public String resourceDistributionTable() {
        String url = "/api/tcc-mes-service/client-api/culture/resource/statistics?orgId="+orgId;
        StringBuilder sb = new StringBuilder("获取图创数据屏-资源分布表：");
        try {
            String responseJson = restTemplate.getForObject(hostname + url,String.class);
            int code = JSON.parseObject(responseJson).getInteger("code");
            if (code == 200 ) {
                String data = JSON.parseObject(responseJson).getString("data");
                sb.append(data);
                List<ResourceDistributionTableParam> list = JSON.parseObject(data, new TypeReference<List<ResourceDistributionTableParam>>() {
                });
                int sum = list.stream().mapToInt(ResourceDistributionTableParam::getCount).sum();
                ResourceDistributionTableParam param = new ResourceDistributionTableParam();
                param.setCount(sum);
                param.setResourceType("总数");
                list.add(param);
                sb.append(",数据获取成功。");
                log.info(sb.toString());
                return JSON.toJSONString(list);
            }
        } catch (Exception e) {
            sb.append(",获取数据失败：").append(e.getMessage());
            log.error(sb.toString());
            throw new RuntimeException(e);
        }
        return null;
    }
    /**
     * 数据屏-最新资源推荐（10条）
     */
    @GetMapping("/latestResourceRecommend")
    @ApiOperation(value = "数据屏-最新资源推荐")
    public String latestResourceRecommend() {
        String url = "/api/tcc-mes-service/client-api/culture/resource/list?orgId="+orgId;
        StringBuilder sb = new StringBuilder();
        try {
            sb.append("获取图创数据屏-最新资源推荐:");
            String responseJson = restTemplate.getForObject(hostname + url,String.class);
            Integer code = JSON.parseObject(responseJson).getInteger("code");
            if (code == 200){
                String data = JSON.parseObject(responseJson).getString("data");
                sb.append(data);
                String text = Jsoup.parse(data).text();
                sb.append(",解析后的数据：").append(text);
                List<latestResourceRecommendParam> list = JSON.parseObject(text, new TypeReference<List<latestResourceRecommendParam>>() {
                });
                list.forEach(val ->{
                    val.setCoverImg(imgOssUrl+val.getCoverImg());
                });
                log.info(sb.toString());
                return JSON.toJSONString(list);
            }
        } catch (RestClientException e) {
            sb.append("获取数据失败：").append(e.getMessage());
            log.error(sb.toString());
            throw new RuntimeException(e);
        }
        return null;
    }
}


